<style scoped>
    .checkLable{color:#e02222;margin-left: 6px;}
    .default-label{width: 100%;line-height: 22px;}
</style>
<template>
   <!-- <h1>新增工程替换</h1>-->
    <div>
        <!--<router-link to="/EngineeringReplacement" style="float: right">-->
            <el-button type="danger" @click="returnIndex" style="float: right" icon="close" size="mini" class="bolder outsideBtnBS"></el-button>
        <!--</router-link>-->
        <el-form :inline="true" :model="updatePlan" ref="updatePlan" style="border-bottom:1px solid #ccc;">
            <!--替换关系申请编号-->
            <el-form-item :label="nowLangue.replaceNumber" >
                <el-input size="mini" disabled v-model="updatePlan.switchCode"></el-input>
            </el-form-item>
            <!--创建人-->
            <el-form-item :label="nowLangue.founder">
                <el-input size="mini" disabled v-model="updatePlan.creator"></el-input>
            </el-form-item>
            <!--创建时间-->
            <el-form-item :label="nowLangue.creationTime" >
                <el-input size="mini" disabled v-model="updatePlan.createTime"></el-input>
            </el-form-item>
        </el-form>
        <div class="default-label">
            <!--备件替换关系明细-->
            <span v-text="nowLangue.spRecDetail"></span>
            <el-checkbox v-model="spareInfor.relation" style="margin-left: 20px;">
                <!--同时建立与被替换备件-->
                <span class="checkLable" v-text="nowLangue.sameRecDetail"></span>
            </el-checkbox>
            <span style="float:right;">
                <!-- 增行-->
                <el-button @click="addLine" type="danger" size="mini" class="bolder outsideBtnBS" style="margin-left:0!important;" v-text="nowLangue.addRow"></el-button>
                <!--保存-->
                <el-button @click="saveSpare(1)" type="danger" size="mini" class="bolder outsideBtnBS" v-text="nowLangue.save"></el-button>
                <!--保存并提交-->
                <el-button @click="saveSpare(2)" type="danger" size="mini" class="bolder outsideBtnBS" v-text="nowLangue.saveAndSubmit "></el-button>
            </span>
        </div>
        <el-table :data="spareSwitchData" border style="width: 100%;">
            <el-table-column type="index" header-align="center" align="center" :label="nowLangue.sequence" width="40"></el-table-column>
            <el-table-column  :label="nowLangue.operate"  width="60" align="center">
                <template scope="scope">
                    <div class="operationItem bolder" @click="deleteLine(scope.$index,scope.row)" v-text="nowLangue.delete"></div>
                </template>
            </el-table-column>
            <!--产品线-->
            <el-table-column prop="productLineName" :label="nowLangue.productLine"  header-align="center" show-overflow-tooltip> </el-table-column>
            <!--替换备件编码-->
            <el-table-column prop="subMaterialCode" :label="nowLangue.repSpareCode"   header-align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="subMaterialName" :label="nowLangue.repSpareName"   header-align="center" show-overflow-tooltip>
            </el-table-column>
            <!--紧急-->
            <el-table-column prop="urgentflag" :label="nowLangue.urgent" header-align="center" width="50" align="center">
                <template scope="scope">
                    <el-checkbox size="mini" v-model="scope.row.urgentflag" ></el-checkbox>
                </template>
            </el-table-column>
            <!--需求替换关系-->
            <el-table-column prop="reqSubType" :label="nowLangue.demandRepRelation" header-align="center" >
                <template scope="scope">
                    <el-select size="mini" clearable :placeholder="nowLangue.pleaseSelect" v-model="scope.row.reqSubType" @change="changeReq(scope.$index)">
                        <el-option v-for="(sL,index) in switchList" :key="index" :label="sL.label" :value="sL.value"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <!--被替换备件编码-->
            <el-table-column prop="materialCode" :label="nowLangue.repdSpareCode" header-align="center" width="180">
                <template scope="scope">
                    <el-input size="mini" class="disabledClick" disabled  v-model="scope.row.materialCode" icon="search" @click="querySpare(scope.$index)"></el-input>
                </template>
            </el-table-column>
            <!--被替换备件名称-->
            <el-table-column prop="materialName" :label="nowLangue.repdSpareName" header-align="center" show-overflow-tooltip>
            </el-table-column>
            <!--说明-->
            <el-table-column prop="description" :label="nowLangue.explain" header-align="center" show-overflow-tooltip>
                <template scope="scope">
                    <el-input size="mini" v-model="scope.row.description" :placeholder="nowLangue.pleaseImport"></el-input>
                </template>
            </el-table-column>
        </el-table>
        <!--选择备件弹窗 选择备件-->
        <v-selectSpare v-on:closeDialog="closeDialog"  v-on:selected-spare="confirmSpare" :dialogVisible="dialogFormVisible"></v-selectSpare>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                nowLangue:{},
                languageScoped:{
                    zh:{
                        "pleaseSelect":"请选择",
                        "pleaseImport":"请输入",
                        "judName":"法人信息",
                        "productLine":"产品线" ,
                        "spareCode":"备件编码",
                        "spareName":"备件名称",
                        "createDate":"创建日期",
                        "to":"至",
                        "query":"查询",
                        "loadDesperately":"拼命加载中",
                        "sequence":"序",
                        "operate":"操作",
                        "addNew":"新增",
                        "submitConfirm":"提交",
                        "replaceNumber":"替换关系申请编号",
                        "founder":"创建人",
                        "creationTime":"创建时间",
                        "delete":"删除",
                        "repSpareCode":"替换备件编码",
                        "repSpareName":"替换备件名称",
                        "urgent":"紧急",
                        "demandRepRelation":"需求替换关系",
                        "repdSpareCode":"被替换备件编码",
                        "repdSpareName":"被替换备件名称",
                        "explain":"说明",
                        "spRecDetail":"备件替换关系明细",
                        "sameRecDetail":"同时建立与被替换备件",
                        "addRow":"增行",
                        "save":"保存",
                        "saveAndSubmit":"保存并提交",
                        "sure":"确定",
                        "chose":"选择"
                    },
                    en:{
                        "pleaseSelect":"please select",
                        "pleaseImport":"please import ",
                        "judName":"jud Name",
                        "productLine":"product Line" ,
                        "spareCode":"spare Code",
                        "spareName":"spare Name",
                        "createDate":"create Date",
                        "to":"to",
                        "query":"query",
                        "loadDesperately":"load Desperately",
                        "sequence":"sequence",
                        "operate":"operate",
                        "addNew":"addNew",
                        "submitConfirm":"submitConfirm",
                        "replaceNumber":"Replace relationship request number",
                        "delete":"delete",
                        "founder":"founder",
                        "creationTime":"creation time",
                        "repSpareCode":"Demand substitution relation",
                        "repSpareName":"Replacement spare parts name",
                        "urgent":"urgent",
                        "demandRepRelation":"Demand substitution relation",
                        "repdSpareCode":"Demand substitution code",
                        "repdSpareName":"Demand substitution name",
                        "explain":"explain",
                        "spRecDetail":"spRecDetail",
                        "sameRecDetail":"sameRecDetail",
                        "addRow":"add row",
                        "save":"save",
                        "saveAndSubmit":"save and submit",
                        "sure":"sure",
                        "chose":"chose"
                    }
                },
                // 查询表单
                updatePlan:{
                    switchCode:"",
                    creator:"",
                    createTime:''
                },
//                relation:false,//同时建立与被替换备件
                formId:"",//查询需要传的参数
                whichQueryFlag:false,//判断刚进入页面时调取哪个查询接口   从哪个接口进入的新增等页面就返回调取那个接口
                spareSwitchData:[],//列表
                saveSpareInfor:{},//暂存原始一条数据，増行时使用
                spareInfor:{},//保存修改查看回的数据，用于修改保存
                createIndex:"",//选择备件的行下标
                switchList:[],//需求替换关系集合
                dialogFormVisible:false,
                updateDisabled:false,
            };
        },
        created:function(){
            this.languageType=="zh"?this.nowLangue=this.languageScoped.zh:this.nowLangue=this.languageScoped.en;
        },
        computed:{
            languageType(){
                return this.$store.state.languageType;
            }
        },
        watch:{
            languageType(){
                this.languageType=="zh"?this.nowLangue=this.languageScoped.zh:this.nowLangue=this.languageScoped.en;
            }
        },
        //进入页面立即运行此方法
        mounted: function () {
            var _this = this;
            _this.$store.commit('currentActive', 'UpdateEReplacement');
            //接收参数
            _this.formId=_this.$route.query.formId;
            this.whichQueryFlag=this.$route.query.whichQueryFlag;
            this.queryOpera();
            this.getCommonList();
            this.queryinfor();
        },
        methods:{
            //下拉框公共接口
            getCommonList(){
                var _this=this;
                var tmp=["substituteFormItem.reqSubType"];
                $.ajax({
                    type: 'POST',
                    url: _this.metadata_service+"metadata/getPullDownList",
                    cache: false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success) {
                            _this.switchList=data.data['substituteFormItem.reqSubType'];//需求替换关系集合
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    }
                })
            },
            //获取创建人员与创建时间
            queryOpera(){
                var _this=this;
                $.ajax({
                    type:'GET',
                    url:_this.metadata_service+'barCode/createInitParameter',
                    cache:false,
                    dataType:'JSON',
                    contentType:"application/json;charset=utf-8",
                    success:function(data){
                        if(data.success){
                            _this.updatePlan.creator=data.data.personName;
                            _this.updatePlan.createTime=data.data.operationTime;
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    }
                })
            },
            //查询信息
            queryinfor(){
                var _this=this;
                _this.loading=true;
                $.ajax({
                    type: 'GET',
                    url: _this.metadata_service+"projectSubstitute/queryProjectSubstituteByFormId?formId="+_this.formId,
                    cache: false,
                    dataType:'JSON',
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success) {
                            _this.spareInfor=data.data;
                            _this.saveSpareInfor=data.data.items[0];
                            _this.spareSwitchData=data.data.items;
                            for(var i=0;i<_this.spareSwitchData.length;i++){
                                _this.spareSwitchData[i].reqSubType=""+_this.spareSwitchData[i].reqSubType;
                            }
                            _this.updatePlan.switchCode=data.data.no;
                        }else{
                            _this.loading=false;
                            _this.common.errorTip(data.errorMessage)
                        }
                    }
                });
            },
            //需求替换关系@change
            changeReq(index){
                if(this.isNull(this.spareSwitchData[index].subMaterialCode)){
                    this.spareSwitchData[index].materialCode="";
                    this.spareSwitchData[index].materialName="";
                }
            },
            // 新增 选择备件弹窗 单选
            querySpare(index){
                this.createIndex=index;
                if(this.isNull(this.spareSwitchData[index].reqSubType)){
                    this.dialogFormVisible = true;
                }else{
                    var err=this.languageType=="zh"?'请先选择需求替换关系！':'Please Select';
                    this.common.errorTip(err);
                }
            },
            //判断被替换数是否重复
            isRepeatCode(value,arr){
                for(var i=0;i<arr.length;i++){
                    if(value==arr[i]){
                        return true
                    }
                }
                return false
            },
            // 选择弹窗的确定按钮
            confirmSpare(selectedSpare){
                this.dialogFormVisible = false;
                //验证相同需求替换关系被替换备件不可以重复
                var reaptArray=[];//互替暂存
                var reaptOnly=[];//单替暂存
                var reaptDis=[];//反替暂存
                for(var i=0;i<this.spareSwitchData.length-1;i++){
                    if(this.spareSwitchData[i].reqSubType==1){
                        reaptArray.push(this.spareSwitchData[i].materialCode);
                    }else if(this.spareSwitchData[i].reqSubType==2){
                        reaptOnly.push(this.spareSwitchData[i].materialCode);
                    }else if(this.spareSwitchData[i].reqSubType==3){
                        reaptDis.push(this.spareSwitchData[i].materialCode);
                    }
                }
                if(this.spareSwitchData[this.createIndex].materialCode==this.spareSwitchData[this.createIndex].subMaterialCode){
                    var errReplace=this.languageType=="zh"?'备件不能替换自身！':'Have Select';
                    this.common.errorTip(errReplace);
                }else{
                    if(this.isRepeatCode(selectedSpare.selectedSpareCode,reaptArray)){
                        var errHad=this.languageType=="zh"?'此备件已存在互替关系！':'Have Select';
                        this.common.errorTip(errHad);
                    }else if(this.isRepeatCode(selectedSpare.selectedSpareCode,reaptOnly)&&this.spareSwitchData[this.createIndex].reqSubType==2){
                        var errHad1=this.languageType=="zh"?'此备件已存在单替关系！':'Have Select';
                        this.common.errorTip(errHad1);
                    }else if(this.isRepeatCode(selectedSpare.selectedSpareCode,reaptDis)&&this.spareSwitchData[this.createIndex].reqSubType==3){
                        var errHad2=this.languageType=="zh"?'此备件已存在反替关系！':'Have Select';
                        this.common.errorTip(errHad2);
                    }else{
                        this.spareSwitchData[this.createIndex].materialCode=selectedSpare.selectedSpareCode;
                        this.spareSwitchData[this.createIndex].materialName=selectedSpare.selectedSpareName;
                    }
                }
            },
            //关闭弹窗
            closeDialog(dialogVisible){
                this.dialogFormVisible = dialogVisible;
            },
            //増行
            addLine(){
                this.spareSwitchData.push({
                    "id":this.saveSpareInfor.id,
                    "formId":this.saveSpareInfor.formId,
                    "productLineName":this.saveSpareInfor.productLineName,
                    "productLineId":this.saveSpareInfor.productLineId,
                    "subMaterialCode":this.saveSpareInfor.subMaterialCode,
                    "subMaterialName":this.saveSpareInfor.subMaterialName,
                    "urgentflag":false,
                    "reqSubType":"",
                    "materialCode":"",
                    "materialName":"",
                    "description":""
                });
            },
            //删除
            deleteLine(index,row){
                this.spareSwitchData.splice(index,1);
            },
            //判断是否为空
            isNull(str){
                if(str=="" || str==null){
                    return false;
                }
                return true
            },
            //parm为1，是保存；2，是保存并提交
            saveSpare(parm){
                var _this=this;
                for(var i in this.spareSwitchData){
                    if(!this.isNull(this.spareSwitchData[i].reqSubType)){
                        var errSub=this.languageType=="zh"?'请选择需求替换关系！':'Have Empty';
                        this.common.errorTip(errSub);
                        return false
                    }
                    if(!this.isNull(this.spareSwitchData[i].materialCode)){
                        var errCode=this.languageType=="zh"?'请选择被替换备件编码！':'Have Empty';
                        this.common.errorTip(errCode);
                        return false
                    }
                }
                _this.updateDisabled=true;
                var tmp={
                    id:this.spareInfor.id,
                    no:_this.spareInfor.no,
                    relation:this.spareInfor.relation,//同时建立与被替换备件
                    productLineId:this.spareInfor.productLineId,//产品线ID
                    materialCode:this.spareInfor.materialCode,//备件编码
                    materialName:this.spareInfor.materialName,//备件名称
                    unit:this.spareInfor.unit,//计量单位
                    status:parm,//状态（保存传1 保存并提交传2）
                    items:this.spareSwitchData
                }
                $.ajax({
                    type:'POST',
                    url:_this.metadata_service+'projectSubstitute/update',
                    cache:false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType:"application/json;charset=utf-8",
                    success:function(data){
                        _this.updateDisabled=false;
                        if(data.success){
                            var successMessage=_this.languageType=="zh"?'保存成功！':'Save Success';
                            _this.common.successTip(successMessage);
                                //保存并提交以后跳转
                            _this.$router.push({ path: 'EngineeringReplacement', query: { whichQueryFlag:_this.whichQueryFlag}})
                        }else if(data.errorCode=="substituteForm.add.exist.substitute.relation"){
                            var errorRelation="";
                            for(var i=0;i<data.hint.length;i++){
                                errorRelation+=data.hint[i].materialCode+" -> " + data.hint[i].subMaterialCode +" "+data.hint[i].reqSubTypeName +'\n';
                            }
                            _this.common.errorTip(data.errorMessage+'\n'+errorRelation);
                        }else if(data.errorCode=="substituteForm.add.exist.same.item"){
                            var errorItem="";
                            for(var i=0;i<data.errorArgs.length;i++){
                                errorItem+=data.errorArgs[i]+",";
                            }
                            _this.common.errorTip(errorItem+ " " + data.errorMessage);
                        }else if(data.errorCode=="substituteForm.add.exist.self2self"){
                            var errorSelf="";
                            for(var i=0;i<data.hint.length;i++){
                                errorSelf+=data.hint[i].materialCode+",";
                            }
                            _this.common.errorTip(errorSelf+ " " + data.errorMessage);
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }
                    },
                    error:function(){
                        _this.updateDisabled=false;
                    }
                })
            },
            returnIndex(){
                this.$router.push({ path: 'EngineeringReplacement', query: { whichQueryFlag:this.whichQueryFlag}})
            }
        }
    }
</script>